import React, {useEffect, useRef, useState} from 'react';
import type {AuthPermission, AuthRoleAddItem} from '../data';
import AuthPermissionConfiguration
  from '@/pages/System/Auth/AuthRole/components/AuthPermissionConfiguration';
import type { ProFormInstance} from '@ant-design/pro-form';
import ProForm, {ModalForm, ProFormText} from '@ant-design/pro-form';
import {fetchConfigurableAuthPermission} from "@/pages/System/Auth/AuthRole/service";

interface AddFormProps {
  onSubmit: (values: AuthRoleAddItem) => Promise<boolean>;
  modalVisible: boolean;
  onVisibleChange: (visible: boolean) => void;
}


const AddForm: React.FC<AddFormProps> = props => {
  const formRef = useRef<ProFormInstance>();
  const [permissions, setPermissions] = useState<AuthPermission[]>([]);
  const {
    onSubmit: handleAdd,
    modalVisible: addModalVisible,
    onVisibleChange
  } = props;

  useEffect(() => {
    fetchConfigurableAuthPermission({}).then(res => {
      setPermissions(res.data || []);
    });

  }, [])

  const onModalOk = async () => {
    const fieldsValue = (await formRef.current?.validateFields()) as AuthRoleAddItem;
    return handleAdd(fieldsValue);
  };

  return (
      <ModalForm
          title='新建角色'
          visible={addModalVisible}
          width={600}
          formRef={formRef}
          onFinish={() => onModalOk()}
          onVisibleChange={onVisibleChange}
      >
        <ProFormText name='name' label='角色名称' rules={[{required: true, message: '必填'}]}/>

        <ProForm.Item name='permissions' label='权限配置'>
          <AuthPermissionConfiguration
              defaultValue={[]}
              sourceValue={permissions}
          />
        </ProForm.Item>
      </ModalForm>
  );
};
export default AddForm;
